package com.queen.testretrofitrxjava.progress;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;

import com.queen.testretrofitrxjava.applications.ApplicationController;

public class ProgressDialogHandler extends Handler {

	public static final String TAG = ProgressDialogHandler.class.getSimpleName();
	
	public static final int SHOW_PROGRESS_DIALOG = 0x001001;
	public static final int DISMISS_PROGRESS_DIALOG = 0x001002;
	
	private Context context;
	private MyProgressDialog pd;

	////ProgressDialog取消监听
	private ProgressCancelListener mProgressCancelListener;

	//ProgressDialog是否可以被取消
	private boolean cancelable;


	public static ProgressDialogHandler getInstance(ProgressCancelListener mProgressCancelListener, boolean cancelable){

		return new ProgressDialogHandler(ApplicationController.getsInstance().getCurrentActivity(), mProgressCancelListener, cancelable);
	}
	
	public ProgressDialogHandler(Context context, ProgressCancelListener mProgressCancelListener,
								 boolean cancelable) {
		super();
		this.context = context;
		this.mProgressCancelListener = mProgressCancelListener;
		this.cancelable = cancelable;
	}
	
	private void initProgressDialog(){
		try{
			if (pd == null) {
				pd = new MyProgressDialog(context);

				pd.setCancelable(cancelable);

				if (cancelable) {
					pd.setOnCancelListener(new DialogInterface.OnCancelListener() {
						@Override
						public void onCancel(DialogInterface dialog) {

							if (mProgressCancelListener != null) {
								mProgressCancelListener.onCancelProgress();
							}
						}
					});
				}

			}
			if (!pd.isShowing()) {
				pd.show();
			}
		} catch (Exception e){

		}

	}
	
	private void dismissProgressDialog(){
		if (pd != null) {
			pd.dismiss();
			pd = null;
		}
	}
	
	@Override
	public void handleMessage(Message msg) {
		switch (msg.what) {
		case SHOW_PROGRESS_DIALOG:
			initProgressDialog();
			break;
		case DISMISS_PROGRESS_DIALOG:
			dismissProgressDialog();
			break;
		}
	}
}
